const { getMessagePage, updateReadState, batchUpdateReadState, messageStatistics, delMessage } = require('../../utils/message');
const { formatDateTime } = require('../../utils/date');
const app = getApp()
Page({
  data: {
    activeTab: '',
    waitReadCount: 0,
    msgList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showActionModal: false,
    actionMsgId: null,
    actionMsgIndex: null,
    currentMessage: {}
  },
  onLoad(options) {
    // 1. 先处理tab参数
    let tab = '';
    if (options && options.tab && (options.tab === '' || options.tab === 'wait_read' || options.tab === 'read')) {
      tab = options.tab;
    }
    this.setData({ activeTab: tab });
    // 更新一下统计数
    this.doMsgStatistics()
    
  },
  doMsgStatistics(){
    // 2. 获取统计数据后再加载消息
    messageStatistics().then(stat => {
      this.setData({
        waitReadCount: stat.waitReadCount || 0,
        // 其它统计数据可用
      });
      this.loadMsgList(true);
    });
  },
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.activeTab) return;
    this.setData({ activeTab: tab, page: 1, hasMore: true, msgList: [] }, () => {
      this.loadMsgList(true);
    });
  },
  onScrollToLower() {
    if (!this.data.hasMore || this.data.loading) return;
    this.loadMsgList();
  },
  loadMsgList(reset) {
    this.setData({ loading: true });
    // 1. 计算分页参数
    const { activeTab, page, pageSize } = this.data;
    let readState = activeTab;
    // 2. 请求数据
    getMessagePage(readState, reset ? 1 : page, pageSize)
      .then(res => {
        // res 应为 { records: [], total: 0, ... } 或数组
        let list = Array.isArray(res) ? res : (res.records || []);
        
        // 格式化消息数据，添加发送时间
        const formattedList = list.map(item => ({
          ...item,
          sendTime: item.sendTime ? formatDateTime(item.sendTime) : ''
        }));
        
        let msgList = reset ? formattedList : this.data.msgList.concat(formattedList);
        const hasMore = list.length === pageSize;
        this.setData({
          msgList,
          loading: false,
          hasMore,
          page: reset ? 2 : page + 1
        });
      })
      .catch(() => {
        this.setData({ loading: false });
        wx.showToast({ title: '加载失败', icon: 'none' });
      });
  },
  /**
   * 点击item项
   * @param {*} e 
   */
  onMsgTap(e) {
    const id = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    const msgList = this.data.msgList.slice(); // 拷贝一份

    // 未读的消息，调用接口更新为已读
    if (msgList[index].readState !== 'read') {
      updateReadState(msgList[index].id)
        .then(() => {
          // 重新刷新当前页
          this.reloadThisPage();
        })
        .catch(() => {
          wx.showToast({ title: '标记已读失败', icon: 'none' });
          // 失败时不弹窗
        });
    } else {
      const currentMessage = msgList[index];
      this.setData({
        showActionModal: true,
        actionMsgId: id,
        actionMsgIndex: index,
        currentMessage
      });
    }
  },
  /**
   * 点击查看的操作
   */
  onViewMsg() {
    const id = this.data.actionMsgId;
    this.setData({ showActionModal: false });
    if (this.data.currentMessage.canClick === 'yes' && this.data.currentMessage.clickPage){
      wx.navigateTo({ url: this.data.currentMessage.clickPage});
    } else {
      wx.showToast({ title: '暂时无法查看', icon: 'none' });
    }
    
  },
  onDeleteMsg() {
    const index = this.data.actionMsgIndex;
    const msgList = this.data.msgList;
    const id = msgList[index].id;
    delMessage(id)
      .then(() => {
        wx.showToast({ title: '删除成功', icon: 'success' });
        this.setData({
          showActionModal: false,
          actionMsgId: null,
          actionMsgIndex: null,
          currentMessage: {}
        });
        // 重新刷新当前页
        this.reloadThisPage();
      })
      .catch(() => {
        wx.showToast({ title: '删除失败', icon: 'none' });
      });
  },
  onCloseActionModal() {
    this.setData({ showActionModal: false });
  },
  onModalTap(e) {
    // 阻止冒泡，防止点击弹窗内容关闭弹窗
  },
  /**
   * 批量更新已读
   */
  onAllRead() {
    batchUpdateReadState()
      .then(() => {
        wx.showToast({ title: '全部已读', icon: 'success' });
        // 重新刷新当前页
        this.reloadThisPage();
      })
      .catch(() => {
        wx.showToast({ title: '批量已读失败', icon: 'none' });
      });
  },
  /**
   * 重新刷新当前页
   */
  reloadThisPage(){
    this.setData({ page: 1, activeTab: '' });
    this.loadMsgList(true);
    // 更新一下统计数
    this.doMsgStatistics()
  }
}); 